from entityinstance import EntityInstance

from collections import OrderedDict

class Entity :
	'''this class represents an entity in a PDB entry'''
	def __init__(s, dataconnector, eid) :
		s.dc, s.eid = dataconnector, eid
		s.initBasic()
	def initBasic(s) :
		'''set basic properties like type, polytype, name'''
		if hasattr(s,'name') : return
		for entdata in s.dc.getCategory("entity",None,"iter") :
			if entdata["id"] != s.eid : continue
			s.name = entdata["pdbx_description"]
			s.type = entdata["type"]
			s.polytype = None
			for epdata in s.dc.getCategory("entity_poly",None,"iter") :
				if epdata["entity_id"] == s.eid : s.polytype = epdata["type"] ; break
			break
	def getEntityId(s) : return s.eid
	def getName(s) : return s.name
	def getPolymerType(s) : return s.polytype
	def isType(s,whichtype) :
		'''answers whether the entity is one of standard entity-types ie polymer, non-polymer, water,
			OR one of standard polymeric-entity-types ie 'other', 'polydeoxyribonucleotide/polyribonucleotide hybrid', 'polysaccharide(D)', 'polypeptide(L)', 'polyribonucleotide', 'polydeoxyribonucleotide', 'polysaccharide(L)', 'polypeptide(D)'
			OR one of simply-named types ie protein, DNA, RNA, DNA-RNA-hybrid, sugar'''
		if whichtype == s.type : return True
		if whichtype == s.polytype : return True
		standard_polymeric_entity_types = ['other', 'polydeoxyribonucleotide/polyribonucleotide hybrid', 'polysaccharide(D)', 'polypeptide(L)', 'polyribonucleotide', 'polydeoxyribonucleotide', 'polysaccharide(L)', 'polypeptide(D)']
		if whichtype in standard_polymeric_entity_types : return False
		if not whichtype in ['polymer', 'non-polymer', 'water', 'protein', 'DNA', 'RNA', 'DNA-RNA-hybrid', 'sugar', 'other'] :
			raise NotImplementedError("type %s is unknown to this function" % whichtype)
		if whichtype == "protein" and "polypeptide(L)" in s.polytype : return True
		if whichtype == "sugar" and "polysaccharide" in s.polytype : return True
		if whichtype == "RNA" and s.polytype == "polyribonucleotide" : return True
		if whichtype == "DNA" and s.polytype == "polydeoxyribonucleotide" : return True
		if whichtype == "DNA-RNA-hybrid" and s.polytype == "polydeoxyribonucleotide/polyribonucleotide hybrid" : return True
		return False
	def getInstances(s) :
		'''return a list of instances'''
		s.prepareInstances()
		return s.instances.values()
	def getInstance(s, said) :
		s.prepareInstances()
		return s.instances[said]
	def prepareInstances(s) :
		'''make ordered dictionary of entity-instances representing each entityId-structAsymId combination'''
		if not hasattr(s, 'instances') :
			s.instances = OrderedDict()
			for sarow in s.dc.getCategory('struct_asym',None,"iter") :
				if sarow["entity_id"] == s.eid : s.instances[sarow["id"]] = EntityInstance(s.dc, s.eid, sarow["id"])
	def getModelledGroups(s) :
		'''returns a list of modelled subgroups belonging to the entity by parsing the atom_site records'''
